package com.example.mvvmdemo.activity.mtv;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.mvvmdemo.R;
import com.example.mvvmdemo.adapter.MyDataViewAdapter;
import com.example.mvvmdemo.databinding.ActivityDatalistBinding;
import com.example.mvvmdemo.databinding.ListMtvDataBinding;
import com.example.mvvmdemo.http.mtv.MtvViewModel;
import com.example.mvvmdemo.model.Mtv;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * User: Chentuisi
 * Date: 2023/8/8
 */
//,EasyPermissions.PermissionCallbacks
public class DataListActivity extends AppCompatActivity implements OnRefreshLoadMoreListener {
    public static final int RC_WRITE_AND_READ_EXTERNAL_STORAGE = 1;
    private MyDataViewAdapter<Mtv,ListMtvDataBinding> myDataViewAdapter;
    private int page = 0;
    private ActivityDatalistBinding binding;
    private MtvViewModel mtvViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_datalist);
        mtvViewModel = new ViewModelProvider(this).get(MtvViewModel.class);
        binding.setLifecycleOwner(this);
        binding.setHandler(this);
        initViewModel();
        initView();
        initData();
        binding.smartrefresh.setOnRefreshLoadMoreListener(this);
        checkReadAndWritePermission(this);
    }

    private void initViewModel(){
        mtvViewModel.getMtvList().observe(this, newList ->{
            if(page == 0){
                myDataViewAdapter.setNewData(newList.getList());
            } else {
                myDataViewAdapter.addData(newList.getList());
            }
            binding.smartrefresh.finishLoadMore();
            binding.smartrefresh.finishRefresh();
        });
    }

    private void initView(){
        View view = findViewById(R.id.iv_re);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        TextView titleTv = findViewById(R.id.tv_title);
        titleTv.setText(R.string.mtv_list_title);
        myDataViewAdapter = new MyDataViewAdapter<Mtv,ListMtvDataBinding>(R.layout.list_mtv_data) {
            @Override
            protected void onBindItem(ListMtvDataBinding binding, int position, Mtv item) {
                binding.setData(item);
                binding.tvNum.setText("序号："+String.valueOf(position+1));
                Glide.with(this.mContext).load(item.getCover()).into(binding.ivCover);
                binding.getRoot().setOnClickListener( view -> {
                    DataDetailActivity.toIntent(mContext,item.getId());
                });
                if(item.isIs_new()){
                    binding.ivNew.setVisibility(View.VISIBLE);
                } else {
                    binding.ivNew.setVisibility(View.INVISIBLE);
                }
                if("".equals(item.getRate())){
                    binding.ivStar.setImageResource(R.mipmap.zero_star);
                } else {
                    switch (item.getRate().substring(0,1)){
                        case "1" :
                            binding.ivStar.setImageResource(R.mipmap.one_star);
                            break;
                        case "2" :
                            binding.ivStar.setImageResource(R.mipmap.one_star);
                            break;
                        case "3" :
                            binding.ivStar.setImageResource(R.mipmap.two_star);
                            break;
                        case "4" :
                            binding.ivStar.setImageResource(R.mipmap.two_star);
                            break;
                        case "5" :
                            binding.ivStar.setImageResource(R.mipmap.three_star);
                            break;
                        case "6" :
                            binding.ivStar.setImageResource(R.mipmap.three_star);
                            break;
                        case "7" :
                            binding.ivStar.setImageResource(R.mipmap.four_star);
                            break;
                        case "8" :
                            binding.ivStar.setImageResource(R.mipmap.four_star);
                            break;
                        case "9" :
                            binding.ivStar.setImageResource(R.mipmap.five_star);
                            break;
                        case "10" :
                            binding.ivStar.setImageResource(R.mipmap.five_star);
                            break;
                        default:
                            break;
                    }
                }
            }
        };
        binding.recyclerview.setHasFixedSize(true);
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        binding.recyclerview.setAdapter(myDataViewAdapter);
        binding.recyclerview.setNestedScrollingEnabled(false);
    }
    private void initData(){
        getData();
    }
    public void getData(){
        mtvViewModel.getMtvList(page);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        getData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 0;
        getData();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //获取读写权限
    public boolean checkReadAndWritePermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()){
                ToastUtils.showShort("获取权限成功");
                return true;
            } else {
                new AlertDialog.Builder(this)
                        .setTitle("申请权限")
                        .setMessage("需要访问文件权限")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                                intent.setData(Uri.parse("package:" + context.getPackageName()));
                                startActivityForResult(intent, RC_WRITE_AND_READ_EXTERNAL_STORAGE);
                                dialogInterface.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                finish();
                            }
                        })
                        .show();

            }
        } else {
            String[] perms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(this, perms)) {
                // Already have permission, do the thing
                // ...
                ToastUtils.showShort("获取权限成功");
                return true;
            } else {
                // Do not have permissions, request them now
                EasyPermissions.requestPermissions(this, "申请权限",
                        RC_WRITE_AND_READ_EXTERNAL_STORAGE, perms);
            }
        }
        return false;
    }

/*    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.d("TAG", "onPermissionsDenied:" + requestCode + ":" + perms.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("需申请权限")
                    .setRationale("请进入设置->权限管理中打开权限")
                    .build().show();
        } else {
            finish();
        }
    }*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_WRITE_AND_READ_EXTERNAL_STORAGE && !checkReadAndWritePermission(this)){
            ToastUtils.showShort("获取权限失败");
        } else {
            ToastUtils.showShort("获取权限成功");
        }
    }
}
